import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';

class RegisterStep2Controller extends GetxController {
  final TextEditingController textEditingController = TextEditingController();
  final phone = Get.arguments["tel"];
  // 倒计时10秒
  var seconds = 10.obs;
  @override
  void onInit() {
    super.onInit();
    countDown();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 开始倒计时
  countDown() {
    // 每秒执行一次
    Timer.periodic(Duration(seconds: 1), (timer) {
      seconds.value--;
      if (seconds.value <= 0) {
        timer.cancel();
      }
    });
  }

  // 重新发送验证码
  sendCode() async {
    var response = await XHttp.getInstance().post(Api.sendCode, {"tel": phone});
    if (response != null) {
      Result result = response as Result;
      if (result.data["success"]) {
        Get.snackbar("提示信息", "验证码发送成功");
        seconds.value = 10;
        countDown();
      } else {
        Get.snackbar("提示信息", "验证码发送失败");
      }
    } else {
      Get.snackbar("提示信息", "验证码发送失败");
    }
  }

  // 验证验证码
  Future<bool> validateCode() async {
    var response = await XHttp.getInstance().post(
        Api.validateCode, {"tel": phone, "code": textEditingController.text});
    if (response != null) {
      seconds.value = 0;
      Result result = response as Result;
      if (result.data["success"]) {
        return true;
      } else {
        return false;
      }
    } else {
      seconds.value = 0;
      return false;
    }
  }
}
